package filter;

import bean.LoginBean;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author VICTOR
 */

@WebFilter(filterName = "FiltroSeguranca", urlPatterns = {"/faces/*"})

public class FiltroSeguranca implements Filter  {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse respHttp = (HttpServletResponse) response;
        HttpServletRequest reqHttp = (HttpServletRequest) request;
        String uri = reqHttp.getRequestURI();
        //System.out.println("Uri: " + uri + " "+ new Date());
        HttpSession session = reqHttp.getSession(false);

        if (uri.matches(".*login\\.xhtml") || uri.matches(".*sistemaagendamento/") || uri.matches(".*\\.css.*") || uri.matches(".*\\.js")) {
            //passam sem validação de autenticação
            chain.doFilter(request, response); //encaminha a requisição para onde ela iria normalmente 
        } else if (session != null && session.getAttribute(LoginBean.FLAG_USUARIO_AUTENTICADO) != null) {
            //só passa se for autentico
            chain.doFilter(request, response);
        } else {
            respHttp.sendRedirect("login.xhtml");
        }

    }

    @Override
    public void destroy() {
    }
}
